package saucaca.Download;

import lemon.kenhnhacvn.BaseEngine;
import saucaca.JSON.WServiceLib;
import saucaca.Object.SongObject;
import saucaca.Util.PreferenceUtils;
import saucaca.Util.TagName;
import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;


public class DownloadTask {
	Context context;
	private DownloadManager mgr = null;
	private long lastDownload = -1L;
	String url_path = "";
	String fileName="music";
	String songName="";
	String nameSinger="";
	SongObject songObject;
	public DownloadTask(Context context, SongObject songObject) {
		this.context = context;
		this.songObject=songObject;
		url_path = songObject.getPATCH_FULL();
		songName = songObject.getTXNAME();
		nameSinger = songObject.getNAME_SINGERS();
		mgr = (DownloadManager) context.getSystemService(context.DOWNLOAD_SERVICE);
		context.registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
		context.registerReceiver(onNotificationClick, new IntentFilter(DownloadManager.ACTION_NOTIFICATION_CLICKED));
	}
	
	@SuppressLint("NewApi")
	public void startDownload() {
		Uri uri = Uri.parse(BaseEngine.checkVideoPath(url_path));
		Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdirs();
		lastDownload = mgr.enqueue(new DownloadManager.Request(uri).setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
				.setAllowedOverRoaming(false).setTitle(songName).setDescription(nameSinger)
				.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName));
		
		new  downloadServices().execute("");
		// v.setEnabled(false);
		// findViewById(R.id.query).setEnabled(true);
	}

	@SuppressLint("NewApi")
	public void queryStatus() {
		Cursor c = mgr.query(new DownloadManager.Query().setFilterById(lastDownload));

		if (c == null) {
			TagName.showToastShort(context, "Download not found!");
		} else {
			c.moveToFirst();

			Log.d(getClass().getName(), "COLUMN_ID: " + c.getLong(c.getColumnIndex(DownloadManager.COLUMN_ID)));
			Log.d(getClass().getName(), "COLUMN_BYTES_DOWNLOADED_SO_FAR: " + c.getLong(c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)));
			Log.d(getClass().getName(), "COLUMN_LAST_MODIFIED_TIMESTAMP: " + c.getLong(c.getColumnIndex(DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP)));
			Log.d(getClass().getName(), "COLUMN_LOCAL_URI: " + c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)));
			Log.d(getClass().getName(), "COLUMN_STATUS: " + c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS)));
			Log.d(getClass().getName(), "COLUMN_REASON: " + c.getInt(c.getColumnIndex(DownloadManager.COLUMN_REASON)));
			TagName.showToastShort(context, statusMessage(c));
		}
	}

	//
	// public void viewLog(View v) {
	// startActivity(new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS));
	// }

	private String statusMessage(Cursor c) {
		String msg = "???";

		switch (c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS))) {
		case DownloadManager.STATUS_FAILED:
			msg = "Download failed!";
			break;

		case DownloadManager.STATUS_PAUSED:
			msg = "Download paused!";
			break;

		case DownloadManager.STATUS_PENDING:
			msg = "Download pending!";
			break;

		case DownloadManager.STATUS_RUNNING:
			msg = "Download in progress!";
			break;

		case DownloadManager.STATUS_SUCCESSFUL:
			msg = "Download complete!";
			break;

		default:
			msg = "Download is nowhere in sight";
			break;
		}

		return (msg);
	}

	BroadcastReceiver onComplete = new BroadcastReceiver() {
		public void onReceive(Context ctxt, Intent intent) {
			// findViewById(R.id.start).setEnabled(true);
			TagName.showToastShort(context, "Đã tải: "+songName);
		}
	};

	BroadcastReceiver onNotificationClick = new BroadcastReceiver() {
		public void onReceive(Context ctxt, Intent intent) {
			Toast.makeText(ctxt, "Đang tải bài hát...", Toast.LENGTH_LONG).show();
		}
	};
	
	class downloadServices extends AsyncTask<String, String, String> {
		@Override
		protected String doInBackground(String... params) {
			String user = PreferenceUtils.getString(context, TagName.KeyPreference_user);
			if (user == null) {
				user="AppAndroid";
			}
			String str = WServiceLib.download(user, songObject.getSONG_ID());
			BaseEngine.showLogformLongString(str);
			return str;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
		}
	}
}
